<%@ page isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="sec"	uri="http://www.springframework.org/security/tags"%>
<html>
	<head>
			<title><spring:message code="index.title" /></title>
			<link rel="stylesheet" type="text/css" href="/css/temporal/login-global.css" />
			<link rel="stylesheet" type="text/css" href="/css/temporal/login-marketplace.css" />
				
		<!-- 
			http://code.google.com/intl/es-ES/apis/maps/documentation/javascript/places.html#place_searches
			http://code.google.com/intl/es-ES/apis/maps/documentation/javascript/places.html -->

			<link rel="stylesheet" type="text/css" href="/css/datatable/demo_page.css" />
			<link rel="stylesheet" type="text/css" href="/css/datatable/demo_table_jui.css" />
			<link rel="stylesheet" type="text/css" href="/themes/smoothness/jquery-ui-1.8.4.custom.css" />
	</head>
	<body>
	
		<script type="text/javascript">
			jQuery(document).ready(function($) {
				$(searchx());
				});
		</script>
		
		<div id="column1">
			<div id="content1">
				<h2>Please, Claim your Place!</h2>
				<p>
					Welcome, you may claim your Place and enjoy with the feedback of your Entity
				</p>
			</div>
			<div id="content2" style="width:280px">
				<h3>Google Map</h3>
				<script type="text/javascript"
					src="//maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
				
				<script type="text/javascript">
				
					var mapOptions; 
					var map;
					var infowindow;
					var placeAutocompleted;
					
					function initialize() {
						
						mapOptions = {
							center: new google.maps.LatLng(40.431701,-3.663359),
							zoom: 13,
							mapTypeId: google.maps.MapTypeId.ROADMAP
						};
						
						map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
		
						var input = document.getElementById('searchTextField');
						var autocomplete = new google.maps.places.Autocomplete(input);
						autocomplete.bindTo('bounds', map);
		
						infowindow = new google.maps.InfoWindow();
						var marker = new google.maps.Marker({
							map: map
						});
		
						google.maps.event.addListener(autocomplete, 'place_changed', function() {
							
							infowindow.close();
							var place = autocomplete.getPlace();
							placeAutocompleted = place;
							if (place.geometry.viewport) {
								map.fitBounds(place.geometry.viewport);
							} else {
								map.setCenter(place.geometry.location);
								map.setZoom(17);  // Why 17? Because it looks good.
							}
		
							var image = new google.maps.MarkerImage(
								place.icon,
								new google.maps.Size(71, 71),
								new google.maps.Point(0, 0),
								new google.maps.Point(17, 34),
								new google.maps.Size(35, 35));
							
							marker.setIcon(image);
							marker.setPosition(place.geometry.location);
		
							var address = '';
							
							if (place.address_components) {
								address = 
									[(place.address_components[0] &&
									  place.address_components[0].short_name || ''),
									 (place.address_components[1] &&
									  place.address_components[1].short_name || ''),
									 (place.address_components[2] &&
									  place.address_components[2].short_name || '')
									].join(' ');
							}
		 
							var content = 
								'' + 
								'<div><strong>' + place.name + '</strong><br>' + 
								address + '</br>' +
								'<a href=\"javascript:claimDao(\'addx\',' + '\''+ placeAutocompleted.id + '\'' + ');\">Add entity</a></br>' +
								'<a href=\"javascript:claimDao(\'deletex\',' + '\'' + placeAutocompleted.id +'\'' + ');\">Delete entity</a>';
							
							infowindow.setContent(content);
							infowindow.open(map, marker);
						
						});
		
						// Sets a listener on a radio button to change the filter type on Places
						// Autocomplete.
						function setupClickListener(id, types) {
							var radioButton = document.getElementById(id);
							google.maps.event.addDomListener(radioButton, 'click', function() {
								autocomplete.setTypes(types);
							});
						}
		
						setupClickListener('changetype-all', []);
						setupClickListener('changetype-establishment', ['establishment']);
						setupClickListener('changetype-geocode', ['geocode']);
					
					}
					google.maps.event.addDomListener(window, 'load', initialize);
		
					function claimDao (action,idplace) {
						$('#claimWarning').hide();
						var values = {};
						console.debug(action);
						values['idplace'] = idplace;
						sendJson(
								values,
								action,
								function(result) { 
									console.debug("Result is: " + result);
									if (result.added) {
										console.debug("Result.added: " + result.added);
										if (result.added == true) {
											$('#claimWarning').hide();
										} else {
											if (result.added == false) {                            	
												$('#claimWarning').show();
											}
										}
									} else {
										if (result.deleted) {
											console.debug("Result.deleted: " + result.deleted);
											if (result.deleted == true) {
												$('#claimWarning').hide();
											} else {
												if (result.deleted == false) {                            	
													$('#claimWarning').show();
												}
											} 
										}
									}
										$(aoDataTableReload());
								}
							);
						
					} 
				</script>
				
				<script type="text/javascript"
					src="//maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
				<div>
					<input id="searchTextField" type="text" size="30">
					<!-- 					
					<input type="radio" name="type" id="changetype-all" checked="checked">
					<label for="changetype-all">All</label>

					<input type="radio" name="type" id="changetype-establishment">
					<label for="changetype-establishment">Establishments</label>
					
					<input type="radio" name="type" id="changetype-geocode">
					<label for="changetype-geocode">Geocodes</lable>
					 -->
				</div>
				<div id="map_canvas" style="height:260px;width:260px;margin-top: 0.6em;"></div>
				<p id="claimWarning" class="error" style="display:none">Problem claimed entity</p>
			</div>
			<div style="float:left;width:600px">
				<h3>Places Table Manager</h3>
				<script type="text/javascript" language="javascript" src="/js/datatable/jquery.dataTables.js"></script>
				<script type="text/javascript" language="javascript" charset="utf-8">
		
					var aoDataTableReload = function () {
						$('#example').dataTable().fnDraw();
					}
					
					var aoDataTransformer = function (aoData){
			            var o = {};
			            var modifiers = ['mDataProp_', 'sSearch_', 'iSortCol_', 'bSortable_', 'bRegex_', 'bSearchable_', 'sSortDir_'];
			            jQuery.each(aoData, function(idx,obj) {
			                if (obj.name) {
			                    for (var i=0; i < modifiers.length; i++) {
			                        if (obj.name.substring(0, modifiers[i].length) == modifiers[i]) {
			                            var index = parseInt(obj.name.substring(modifiers[i].length));
			                            var key = 'a' + modifiers[i].substring(0, modifiers[i].length-1);
			                            if (!o[key]) {o[key] = [];}
			                            o[key][index] = obj.value;
			                            return;
			                        }
			                    }
			                    o[obj.name] = obj.value;
			                }
			                else {
			                    o[idx] = obj;
			                }
			            });
			            var returnjson = JSON.stringify(o);
			            console.debug (returnjson);
			            return returnjson;
			        };
			        
			        
			 		var searchx = function() {
						$('#example').dataTable({
							"bProcessing" : true,
							"bServerSide" : true,
							"sAjaxSource": "/claim/searchx",
		 					"aoColumns": [
								{ "mDataProp": "idPlace" },
								{ "mDataProp": "tipoEntityClient" },
								{ "mDataProp": "username" },
								{ "mDataProp": null }
							],	 			
							/* 
							"fnServerParams": function ( aoData ) {
								  aoData.push( { "name": "more_data", "value": "my_value" } );
								},*/						
							"fnServerData" : function(sSource, aoData, fnCallback) {
								$.ajax({
				                    contentType: "application/json;charset=UTF-8",							
									type: "POST",
									url : sSource,
									data : aoDataTransformer(aoData),
									success : fnCallback,
									error : function (e){console.debug ("Evento error de ajax: " + e);}, 
									dataType : "json",
									statusCode: {
									    400: function() {
				                        	$(aoDataTableReload());									    	
										    alert('No existen entidades en este username');
										}
									}
								});
							},
						  "fnRowCallback": function( nRow, aData,iDisplayIndex  ) {
								/*http://www.datatables.net/release-datatables/examples/advanced_init/row_callback.html*/
								var aDatakeyQRCode = encodeURIComponent(aData.keyQRCode);
								$('td:eq(3)', nRow).html( '<a href="/qrcode/generateQRCode?key='+aDatakeyQRCode+'" target="_blanck"><img width="30" height="30" src="/qrcode/generateQRCode?key='+aDatakeyQRCode+'"/></a>' );						
					            return nRow;
					        },
					      "bJQueryUI": true,
						   "sPaginationType": "full_numbers"
						});
					};
				</script>	
				
				<div id="dt_example"> 
					<div id="container">
						<div id="dynamic">
		
							<table cellpadding="0" cellspacing="0" border="0" class="display"
								id="example">
								<thead>
									<tr>
										<th width="25%">ID Place</th>
										<th width="25%">Place Source</th>
										<th width="25%">User</th>
										<th width="25%">Download QR Code</th>
									</tr>
								</thead>
								<tbody>
									<tr>
										<td colspan="5" class="dataTables_empty">Loading data from
											server</td>
									</tr>
								</tbody>
								<tfoot>
									<tr>
										<th width="25%">ID Place</th>
										<th width="25%">Place Source</th>
										<th width="25%">User</th>
										<th width="25%">Download QR Code</th>
									</tr>
								</tfoot>
							</table>
						</div>
					</div>
				</div>
			</div>
			<br class="clear-all" />
		</div>		
	</body>
</html>		